package org.iteam.xlz.core.service.user;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.iteam.db.BaseService;
import org.iteam.xlz.core.entity.user.UserInfo;

public class UserInfoService extends BaseService<UserInfo>{
	
	static UserInfoService instance;
	
	private List<Object> params=new ArrayList<Object>();
	private StringBuilder sql=null;
	
	private UserInfoService(){}
	
	public static UserInfoService getInstance(){
		if(null==instance){
			instance=new UserInfoService();
		}
		return instance;
	}
	
	public UserInfo findByMobile(String mobile){
		try {
			return super.show("select l.* from USERINFO l left join MEMBERSHIPCARD r on l.uid=r.uid where 1=1 and l.mobile=? and r.mid is null;",mobile);
		} catch (SQLException e) {
			e.printStackTrace();
			return new UserInfo();
		}
	}
	
	public UserInfo findByUid(String uid){
		try {
			return super.show("select l.* from USERINFO l  where 1=1 and l.uid=?",uid);
		} catch (SQLException e) {
			e.printStackTrace();
			return new UserInfo();
		}
	}
	
	public long counts(String username,String mobile,String qq,String wechat){
		params.clear();
		sql=new StringBuilder("select count(1) from userinfo where 1=1");
		if(StringUtils.isNotBlank(username)){
			sql.append(" and username like ?");
			params.add("%"+username+"%");
		}
		if(StringUtils.isNotBlank(mobile)){
			sql.append(" and mobile like ?");
			params.add("%"+mobile+"%");
		}
		if(StringUtils.isNotBlank(qq)){
			sql.append(" and qq like ?");
			params.add("%"+qq+"%");
		}
		if(StringUtils.isNotBlank(wechat)){
			sql.append(" and wechat like ?");
			params.add("%"+wechat+"%");
		}
		try {
			return super.counts(sql.toString(),params.toArray());
		} catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}
	}
	
	public List<UserInfo> query(String username,String mobile,String qq,String wechat,long page,long rows){
		params.clear();
		sql=new StringBuilder("select * from userinfo where 1=1");
		if(StringUtils.isNotBlank(username)){
			sql.append(" and username like ?");
			params.add("%"+username+"%");
		}
		if(StringUtils.isNotBlank(mobile)){
			sql.append(" and mobile like ?");
			params.add("%"+mobile+"%");
		}
		if(StringUtils.isNotBlank(qq)){
			sql.append(" and qq like ?");
			params.add("%"+qq+"%");
		}
		if(StringUtils.isNotBlank(wechat)){
			sql.append(" and wechat like ?");
			params.add("%"+wechat+"%");
		}
		sql.append(" order by createtime desc limit ?,?");
		params.add((page-1)*rows);
		params.add(rows);
		try {
			return super.query(sql.toString(),params.toArray());
		} catch (SQLException e) {
			e.printStackTrace();
			return new ArrayList<UserInfo>();
		}
	}
}
